package com.lanyam.travel.base.aspect;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aliyuncs.utils.StringUtils;
import com.lanyam.travel.base.annotation.NoRepeatSubmit;
import com.lanyam.travel.base.utils.JSONResult;
import com.lanyam.travel.base.utils.MD5Utils;
import com.lanyam.travel.base.utils.RedisUtil;
 
/**
 * @功能描述 aop解析注解
 * @author www.gaozz.club
 * @date 2018-11-02
 */
@Aspect
@Component
public class NoRepeatSubmitAop {
 
    private Log logger = LogFactory.getLog(NoRepeatSubmitAop.class);
 
    @Resource
    private RedisUtil redisUtil; 
 
    @Around("execution(* com.lanyam..*Controller.*(..)) && @annotation(nrs)")
    public Object arround(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
            //token+method构成key
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("Authorization");
            if(StringUtils.isEmpty(token))
            {
            	return JSONResult.errorMsg("未获取到登陆信息");
            }
            token = MD5Utils.decodeBase64String(token);
            String key = token + "-" + request.getServletPath();
            if (null == redisUtil.get(key)) {// 如果缓存中有这个url视为重复提交
                Object o = pjp.proceed();
                redisUtil.set(key, 0, 2);
                return o;
            } else {
                logger.error("重复提交");
                return JSONResult.errorMsg("表单不能重复提交");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("验证重复提交时出现未知异常!");
            return JSONResult.errorMsg("验证重复提交时出现未知异常!");
        }
 
    }
 
}
